package com.itheima.mp.domain.dto;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * ClassName: PageDTO
 * Description:
 *
 * @Author HL
 * @Create 2024/7/9 14:29
 * @Version 1.0
 */
@Data
@Schema(description = "分页结果")
public class PageDTO<T> {
    @Schema(description = "总条数")
    private Long total;
    @Schema(description = "总页数")
    private Long pages;
    @Schema(description = "集合")
    private List<T> list;

    public static <PO, VO> PageDTO<VO> of(Page<PO> p, Function<PO, VO> convertor){
        PageDTO<VO> dto = new PageDTO<>();
        //1 准备总条数和总页数
        dto.setTotal(p.getTotal());
        dto.setPages(p.getPages());
        //2 当前页数据
        List<PO> records = p.getRecords();
        if(CollUtil.isEmpty(records)){
            dto.setList(Collections.emptyList());
        }
        //3 拷贝user的VO
        List<VO> vos = records.stream().map(convertor).collect(Collectors.toList());
        dto.setList(vos);
        //4. 返回
        return dto;
    }
}
